import axios from "axios";
import router from '../router/router.js';
import VueCookies from 'vue-cookies';
import { message } from 'ant-design-vue';

// 添加JWT解析函数
const parseJwt = (token) => {
  try {
    return JSON.parse(atob(token.split('.')[1]));
  } catch (e) {
    return null;
  }
};

const instance = axios.create({
    baseURL: "/api",
    timeout: 500000,
    withCredentials: true  // 确保跨域请求时发送cookies
});

// 请求拦截器
instance.interceptors.request.use(config => {
    // 排除不需要token的请求
    if (config.url !== '/register' && config.url !== '/authenticate') {
        const jwt = VueCookies.get('jwt');
        const username = VueCookies.get('username');

        if (jwt) {
            // 解析JWT获取claims
            const claims = parseJwt(jwt);
            if (claims) {
                config.headers["Authorization"] = `Bearer ${jwt}`;
                // 如果是授权请求，从claims中获取secret
                if (config.url === '/grant/approveGrantRequest') {
                    if (!config.data) config.data = {};
                    config.data.grantorSecret = claims.userSecret;
                }
            }
        }
        
        if (username) {
            config.headers["username"] = username;
        }
    }
// 如果不是FormData，则设置Content-Type
if (!(config.data instanceof FormData)) {
    config.headers["Content-Type"] = "application/json";
}

// 添加缓存控制头部
if (config.url.startsWith('/download/file')) {
    config.headers['Cache-Control'] = 'no-cache';
    config.headers['Pragma'] = 'no-cache';
}

return config;
    return config;
}, error => {
    return Promise.reject(error);
});

// 响应拦截器
instance.interceptors.response.use(
    response => response,
    error => {
        // 只在开发环境下打印详细错误信息
        if (import.meta.env.DEV) {
            console.error('Response Error:', error.message);
            if (error.response?.status) {
                console.error('Response Status:', error.response.status);
            }
        }

        if (error.response?.status === 401) {
            // 清除登录状态
            sessionStorage.removeItem('isLogin');
            VueCookies.remove('jwt');
            VueCookies.remove('userAddress');
            VueCookies.remove('userSecret');
            VueCookies.remove('username');
            
            message.error('登录已过期，请重新登录');
            
            // 跳转到登录页
            router.push('/login');
        }
        return Promise.reject(error);
    }
);

export default instance;